<template>
  <el-aside
    v-model:collapsed="collapsed"
    :width="collapsed ? '64px' : '200px'"
    class="sidebar"
    transition-duration="300"
  >
    <div class="logo-container">
      <div class="logo">
        <img
          v-if="!collapsed"
          src="/static/images/logo.png"
          alt="Logo"
        />
        <span
          v-if="!collapsed"
          class="logo-text"
        >直律案管</span>
      </div>
    </div>
    <el-menu
      v-if="!menuStore.isMenuLoading"
      class="sidebar-menu"
      :default-active="activeMenu"
      :collapse="collapsed"
      background-color="#001529"
      text-color="#fff"
      active-text-color="#409EFF"
      collapse-transition
      @select="handleMenuClick"
    >
      <template
        v-for="menu in menuStore.menuList"
        :key="menu.id"
      >
        <!-- 无子菜单的顶级菜单项 -->
        <el-menu-item
          v-if="!menu.children || menu.children.length === 0"
          :index="menu?.mig_src || ''"
          @click="handleMenuItemClick(menu)"
        >
          <el-icon :size="18">
            <component :is="getIcon(menu.icon)" />
          </el-icon>
          <template #title>
            {{ menu.title }}
          </template>
        </el-menu-item>

        <!-- 有子菜单的顶级菜单项 -->
        <el-sub-menu
          v-else
          :index="menu.id.toString()"
          @click="handleSubMenuClick(menu, $event)"
        >
          <template #title>
            <el-icon :size="18">
              <component :is="getIcon(menu.icon)" />
            </el-icon>
            <span>{{ menu.title }}</span>
          </template>

          <!-- 遍历二级菜单 -->
          <template
            v-for="subMenu in menu.children"
            :key="subMenu.id"
          >
            <!-- 无子菜单的二级菜单项 -->
            <el-menu-item
              v-if="!subMenu.children || subMenu.children.length === 0"
              :index="subMenu?.mig_src || ''"
              @click="handleMenuItemClick(subMenu)"
            >
              <template #title>
                {{ subMenu.title }}
              </template>
            </el-menu-item>

            <!-- 有子菜单的二级菜单项（三级菜单） -->
            <el-sub-menu
              v-else
              :index="subMenu.id.toString()"
              @click="handleSubMenuClick(subMenu, $event)"
            >
              <template #title>
                {{ subMenu.title }}
              </template>
              <!-- 遍历三级菜单 -->
              <template
                v-for="thirdLevelMenu in subMenu.children"
                :key="thirdLevelMenu.id"
              >
                <el-menu-item
                  :index="thirdLevelMenu?.mig_src || ''"
                  @click="handleMenuItemClick(thirdLevelMenu)"
                >
                  <template #title>
                    {{ thirdLevelMenu.title }}
                  </template>
                </el-menu-item>
              </template>
            </el-sub-menu>
          </template>
        </el-sub-menu>
      </template>
    </el-menu>
    <div
      v-else
      class="menu-loading"
    >
      <el-skeleton
        active
        :count="3"
      />
    </div>
  </el-aside>
</template>

<script setup>
  import { watch, computed, onMounted, ref, markRaw } from 'vue'
  import { useRoute, useRouter } from 'vue-router'
  import { useMenuStore } from '../../store/menu'
  import { ElMessage } from 'element-plus'
  import * as ElementPlusIconsVue from '@element-plus/icons-vue'
  import { updateMenuMigSrc } from '@/services/menu'

  const route = useRoute()
  const router = useRouter()
  const menuStore = useMenuStore()

  // 侧边栏折叠状态
  /** @type {import('vue').ModelRef<boolean>} */
  const collapsed = defineModel('collapsed', { required: true })

  // 当前激活的菜单
  const activeMenu = computed(() => {
    const path = route.path || '/home'
    return path
  })

  // 自动导入所有Element Plus图标
  /** @type {import('vue').Ref<Record<string, any>>} */
  const iconMap = ref({})

  // 初始化图标映射表
  const initIconMap = () => {
    // 确保iconMap是一个响应式对象
    if (!iconMap.value) {
      iconMap.value = {}
    }

    // 将所有Element Plus图标添加到映射表中，使用markRaw避免组件被转为响应式对象
    for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
      iconMap.value[key] = markRaw(component)
    }

    // 添加一些常用的别名映射，兼容旧代码
    const aliases = {
      home: 'HomeFilled',
      document: 'Document',
      user: 'User',
      management: 'Management',
      folder: 'Folder',
      setting: 'Setting',
      message: 'Message',
      calendar: 'Calendar',
      'file-text': 'Files',
      'pie-chart': 'PieChart',
      grid: 'Grid',
      'icon-changguanli': 'Grid',
      'icon-jianchaguanli': 'Document',
      Office: 'OfficeBuilding',
      Tickets: 'Tickets',
      User: 'User',
      UserFilled: 'UserFilled',
      Setting: 'Setting',
      SetUp: 'Setting',
      Money: 'Money',
      Briefcase: 'Briefcase',
      DocumentCopy: 'Document',
      DataLine: 'DataAnalysis',
      FolderOpened: 'FolderOpened',
      // 基于Element Plus官方图标列表添加更多映射关系
      // Arrow相关
      ArrowLeft: 'ArrowLeft',
      ArrowUp: 'ArrowUp',
      ArrowRight: 'ArrowRight',
      ArrowDown: 'ArrowDown',
      ArrowLeftBold: 'ArrowLeftBold',
      ArrowUpBold: 'ArrowUpBold',
      ArrowRightBold: 'ArrowRightBold',
      ArrowDownBold: 'ArrowDownBold',
      DArrowLeft: 'DArrowLeft',
      DArrowRight: 'DArrowRight',

      // Document相关
      DocumentAdd: 'DocumentAdd',
      Notebook: 'Notebook',
      Memo: 'Memo',
      Collection: 'Collection',
      Postcard: 'Postcard',
      DataBoard: 'DataBoard',
      DataAnalysis: 'DataAnalysis',
      CopyDocument: 'CopyDocument',
      FolderChecked: 'FolderChecked',
      Files: 'Files',
      Folder: 'Folder',
      FolderDelete: 'FolderDelete',
      FolderRemove: 'FolderRemove',
      DocumentRemove: 'DocumentRemove',
      FolderAdd: 'FolderAdd',

      // Media相关
      Microphone: 'Microphone',
      VideoCamera: 'VideoCamera',
      Headset: 'Headset',
      Monitor: 'Monitor',
      Camera: 'Camera',
      Picture: 'Picture',

      // Traffic相关
      Location: 'Location',
      OfficeBuilding: 'OfficeBuilding',
      Guide: 'Guide',
      Place: 'Place',

      // Food相关
      Coffee: 'Coffee',
      Dish: 'Dish',
      IceDrink: 'IceDrink',
      IceCream: 'IceCream',
      Food: 'Food',
      Apple: 'Apple',

      // Items相关
      Printer: 'Printer',
      Calendar: 'Calendar',
      CreditCard: 'CreditCard',
      Box: 'Box',
      Brush: 'Brush',
      Suitcase: 'Suitcase',
      SuitcaseLine: 'SuitcaseLine',
      Umbrella: 'Umbrella',
      AlarmClock: 'AlarmClock',
      Medal: 'Medal',
      Present: 'Present',
      Key: 'Key',
      ShoppingCart: 'ShoppingCart',
      ShoppingBag: 'ShoppingBag',
      Phone: 'Phone',
      Scissor: 'Scissor',
      Goods: 'Goods',
      Trophy: 'Trophy',
      Stopwatch: 'Stopwatch',
      Timer: 'Timer',
      CollectionTag: 'CollectionTag',
      PriceTag: 'PriceTag',
      Opportunity: 'Opportunity',

      // Weather相关
      Sunny: 'Sunny',
      Cloudy: 'Cloudy',
      PartlyCloudy: 'PartlyCloudy',
      Moon: 'Moon',

      // Other相关
      Bell: 'Bell',
      Star: 'Star',
      Help: 'Help',
      Shop: 'Shop',

      // 状态相关
      Check: 'Check',
      CircleCheck: 'CircleCheck',
      Warning: 'Warning',
      CircleClose: 'CircleClose',
      Close: 'Close',
      Remove: 'Remove',
      SuccessFilled: 'SuccessFilled',
      WarningFilled: 'WarningFilled',
      CircleCloseFilled: 'CircleCloseFilled',
      InfoFilled: 'InfoFilled',

      // 操作相关
      Edit: 'Edit',
      EditPen: 'EditPen',
      Delete: 'Delete',
      Search: 'Search',
      Download: 'Download',
      Upload: 'Upload',
      ZoomIn: 'ZoomIn',
      ZoomOut: 'ZoomOut',
      Refresh: 'Refresh',
      Sort: 'Sort',
      SortUp: 'SortUp',
      SortDown: 'SortDown',
      Loading: 'Loading',

      // 其他可能用到的图标
      ChatLineRound: 'ChatLineRound',
      ChatDotRound: 'ChatDotRound',
      ChatDotSquare: 'ChatDotSquare',
      ChatLineSquare: 'ChatLineSquare',
      ChatSquare: 'ChatSquare',
      DocumentDelete: 'DocumentDelete',
      DocumentChecked: 'DocumentChecked',
      FirstAidKit: 'FirstAidKit',
      Reading: 'Reading',
      Magnet: 'Magnet',
      Platform: 'Platform',
      TurnOff: 'TurnOff',
      Wallet: 'Wallet',
      Flag: 'Flag',
      BrushFilled: 'BrushFilled',
      Sell: 'Sell',
      SoldOut: 'SoldOut',
    }

    // 将别名添加到映射表中
    for (const [alias, iconName] of Object.entries(aliases)) {
      // 确保目标图标存在再添加别名映射
      if (iconMap.value[iconName]) {
        iconMap.value[alias] = iconMap.value[iconName]
      } else {
        // 如果目标图标不存在，尝试直接使用别名作为图标名称
        if (iconMap.value[alias]) {
          iconMap.value[iconName] = iconMap.value[alias]
        }
      }
    }

    // 打印所有可用的图标名称，方便调试
  }

  // 获取图标组件
  /**
   * @param {string} iconName
   * @returns {any}
   */
  const getIcon = iconName => {
    if (!iconName) return markRaw(ElementPlusIconsVue.HomeFilled)

    // 确保iconMap已初始化
    if (!iconMap.value || Object.keys(iconMap.value).length === 0) {
      initIconMap()
    }

    // 直接查找图标名称
    if (iconMap.value[iconName]) {
      return iconMap.value[iconName]
    }

    // 处理前缀
    if (iconName.startsWith('icon-')) {
      const cleanName = iconName.slice(5)
      if (iconMap.value[cleanName]) {
        return iconMap.value[cleanName]
      }
    }

    // 尝试查找图标名称对应的Element Plus组件
    // 例如：尝试将 'home' 转换为 'Home', 'HomeFilled', 'home-filled' 等形式
    const variations = [
      iconName,
      iconName.charAt(0).toUpperCase() + iconName.slice(1),
      iconName.replace(/-([a-z])/g, g => g[1].toUpperCase()),
      iconName.replace(/-([a-z])/g, g => g[1].toUpperCase()) + 'Filled',
      iconName + 'Filled',
    ]

    for (const variant of variations) {
      if (iconMap.value[variant]) {
        return iconMap.value[variant]
      }
    }

    // 特殊处理：尝试移除"icon-"前缀后再查找
    if (iconName.startsWith('icon-')) {
      const baseName = iconName.substring(5)
      const baseVariations = [
        baseName,
        baseName.charAt(0).toUpperCase() + baseName.slice(1),
        baseName.replace(/-([a-z])/g, g => g[1].toUpperCase()),
      ]

      for (const variant of baseVariations) {
        if (iconMap.value[variant]) {
          return iconMap.value[variant]
        }
      }
    }

    // 双重检查：尝试在ElementPlusIconsVue中直接查找
    const directMatch = ElementPlusIconsVue[iconName]
    if (directMatch) {
      return markRaw(directMatch)
    }

    // 如果都找不到，返回默认图标
    return markRaw(ElementPlusIconsVue.HomeFilled)
  }

  // 处理菜单点击事件
  /**
   * @param {string} key
   */
  const handleMenuClick = async key => {
    // 此方法保留但不再使用，改为使用handleMenuItemClick和handleSubMenuClick
  }

  // 处理无子菜单的菜单项点击
  /**
   * @param {any} menu
   */
  const handleMenuItemClick = async menu => {
    try {
      // 确保菜单对象存在
      if (!menu) {
        ElMessage.warning('菜单数据异常')
        return
      }
      // 获取菜单路径
      let path = menu?.mig_src || ''

      if (!path) {
        // 对于没有明确路径的菜单，尝试使用其他可能的字段或提供默认路径
        path = menu.path || menu.url || '/workbench'
        if (!path) {
          ElMessage.error('菜单路径配置错误，无法获取有效的导航路径')
          return
        }
      }

      // 定义路径映射表，处理特殊路径跳转
      /** @type {Record<string, string>} */
      const pathMap = {
        '/workbench/index': '/workbench',
        '/contract/contract': '/contract/sale-contract',
        '/contract/contract/list': '/contract/sale-contract',
        '/contract/contract_approve_list': '/contract/contract-approval',
        '/contract/contract_wait_approve_list': '/contract/contract-approval',
        '/contract/contract/archivelist': '/contract/contract-archive',
        '/contract/contract/stoplist': '/contract/contract-stop',
        '/contract/contract/voidlist': '/contract/contract-void',
        '/contract/contract_index': '/contract/contract_list',
        '/contract/contract_detail': '/contract/contract_view',
        '/purchase/purchase_detail': '/purchase/purchase_view',
      }

      try {
        // 应用特殊路径映射
        if (pathMap[path]) {
          path = pathMap[path]
        }

        // 确保路径格式正确
        if (!path.startsWith('/')) {
          // 如果是相对路径，添加前导斜杠
          path = '/' + path
        } else if (path.includes('/src/')) {
          // 如果路径包含/src/，去除/src/前缀
          path = path.replace('/src/', '/')
        }

        // 修复可能出现的多个连续斜杠问题
        path = path.replace(/\/+/g, '/')

        // 确保不以斜杠结尾（除非是根路径）
        if (path.length > 1 && path.endsWith('/')) {
          path = path.slice(0, -1)
        }

        // 验证最终路径的有效性
        if (!path || path.length < 1) {
          throw new Error('无效的路径')
        }
      } catch (formatError) {
        ElMessage.error('菜单路径格式错误')
        return
      }

      // 获取当前激活的路由路径
      const currentPath = route.path

      // 如果路由已经激活，则不重复跳转
      if (path !== currentPath) {
        try {
          // 改进路由检查逻辑，处理嵌套路由
          let matchedRoute = router.getRoutes().find(r => r.path === path)

          // 如果找不到完全匹配的路由，尝试使用路由匹配功能检查路径是否有效
          if (!matchedRoute) {
            // 不再预先检查路由是否存在，直接尝试跳转
            // 这样可以让Vue Router自己处理嵌套路由匹配
            try {
              await router.push(path)
              return
            } catch (pushError) {
              ElMessage.error(`路由路径不存在: ${path}`)
              return // 终止后续操作
            }
          }

          // 如果菜单没有mig_src字段，这是异常情况，记录错误
          if (!menu?.mig_src) {
            try {
              // 注释掉API调用，避免在修复阶段产生额外的网络请求
              // const result = await updateMenuMigSrc(menu.id);
              // 后续可以重新启用此功能
            } catch (apiError) {
              // API更新失败不影响页面跳转，只记录警告
            }
          }

          // 强制重置router-view，确保组件重新加载
          const resetView = () => {
            // 创建一个临时key，强制router-view重新渲染
            const viewKey = Date.now()
            sessionStorage.setItem('routerViewKey', viewKey.toString())
          }

          resetView()

          // 使用push而不是replace，确保浏览器历史记录正确
          await router.push(path)

          // 延迟更新激活菜单状态
          setTimeout(() => {
            menuStore.setActiveMenu(path)
          }, 100)
        } catch (err) {
          // 增强错误处理，提供更详细的错误信息
          if (err.name === 'NavigationDuplicated') {
            // 重复导航，忽略
          } else if (
            err.message &&
            err.message.includes('Failed to fetch dynamically imported module')
          ) {
            ElMessage.error('页面组件加载失败，请刷新页面重试')
            // 尝试强制刷新当前路由
            router.replace(route.path)
          } else if (err.message && err.message.includes('Cannot find module')) {
            ElMessage.error('页面组件不存在，请联系管理员')
          } else {
            ElMessage.error('页面跳转失败: ' + (err.message || '未知错误'))

            // 不再使用window.location作为备用方案，保持路由一致性
            // router.push失败时应直接提示错误，不进行额外的跳转操作
          }
        }
      } else {
        // 当前路由已激活，不进行任何操作，避免全页面刷新
        // router.go(0); // 这会导致全页面刷新，已注释掉
        return
      }
    } catch (error) {
      ElMessage.error('菜单操作失败')
    }
  }

  // 处理有子菜单的菜单项点击
  /**
   * @param {any} menu
   * @param {Event} event
   */
  const handleSubMenuClick = (menu, event) => {
    try {
      // 确保菜单对象存在
      if (!menu) {
        ElMessage.warning('菜单数据异常')
        return
      }

      // 阻止事件冒泡，防止触发菜单选择事件
      event.stopPropagation()

      // 对于有子菜单的菜单项，仅展开/收起子菜单，不进行页面跳转
      // Element Plus的el-sub-menu组件已经内置了展开/收起功能
      // 这里只需要阻止默认的路由跳转行为即可

      // 可以在这里添加额外的逻辑，如记录展开状态等
    } catch (error) {
      ElMessage.error('菜单操作失败')
    }
  }

  // 加载菜单数据
  const loadMenus = async (forceRefresh = false) => {
    try {
      // 先检查是否已登录，未登录则不加载菜单
      const token = localStorage.getItem('token')
      if (!token) {
        return // 未登录，不加载菜单
      }

      const result = await menuStore.loadMenuList(forceRefresh)
      // 不再使用 !result 判断，因为 loadMenuList 已经处理了错误情况
      if (result === false) {
        // 避免重复提示，只在必要时提示
        ElMessage.warning('菜单加载失败，请刷新页面重试')
      }

      // 打印加载的菜单数据，方便调试
    } catch (error) {
      // 捕获异常并提示
      ElMessage.error('加载菜单失败')
    }
  }

  // 组件挂载时初始化
  onMounted(() => {
    try {
      // 初始化图标映射表
      initIconMap()
      // 加载菜单
      loadMenus()
    } catch (error) {
      ElMessage.error('侧边栏初始化失败，请刷新页面重试')
    }
  })

  // 监听用户登录状态变化，确保切换账号后重新加载菜单
  let previousToken = localStorage.getItem('token') || ''
  watch(
    () => localStorage.getItem('token') || '',
    newToken => {
      if (newToken !== previousToken) {
        previousToken = newToken
        // 延迟加载菜单，确保用户信息已经更新
        setTimeout(() => {
          // 清除菜单缓存，确保加载最新的菜单
          localStorage.removeItem('menu_list')
          localStorage.removeItem('menuList')
          // 强制重新加载菜单
          loadMenus(true)
        }, 300)
      }
    }
  )

  // 监听菜单数据变化，确保菜单能够正确显示
  watch(
    () => menuStore.menuList,
    newMenus => {
      if (newMenus && newMenus.length > 0) {
        // 菜单数据已更新，确保路由正确高亮
        menuStore.setActiveMenu(route.path)
      }
    },
    { deep: true }
  )

  // 监听路由跳转，确保在登录后等关键跳转时重新加载菜单
  watch(
    () => route.path,
    newPath => {
      menuStore.setActiveMenu(newPath)
      // 如果是从登录页跳转过来，重新加载菜单
      if (newPath === '/home' || newPath.startsWith('/dashboard') || newPath !== previousPath) {
        // 增加对路径变化的监听
        // 稍微延迟一下，确保用户信息已经加载完成
        setTimeout(() => {
          loadMenus(true) // 使用强制刷新参数
        }, 300)
      }
      previousPath = newPath
    }
  )

  // 记录之前的路由路径
  let previousPath = route.path || ''
</script>

<style scoped>
  .sidebar {
    background-color: #001529;
    height: 100%;
    position: relative;
    z-index: 1001;
    box-shadow: 2px 0 8px 0 rgba(29, 35, 41, 0.05);
    padding-right: 0; /* 移除右侧内边距 */
    margin-right: 0; /* 移除右侧外边距 */
    border-right: none; /* 移除右侧边框 */
    display: flex;
    flex-direction: column;
    overflow: hidden; /* 确保侧边栏本身不产生滚动条 */
  }

  .logo-container {
    height: 64px;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: #002140;
    flex-shrink: 0; /* 防止logo区域被压缩 */
  }

  .logo {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 100%;
  }

  .logo img {
    height: 32px;
    transition: all 0.3s;
  }

  .logo-text {
    margin-left: 12px;
    font-size: 18px;
    font-weight: 600;
    color: white;
    transition: all 0.3s;
    white-space: nowrap;
    overflow: hidden;
  }

  .menu-loading {
    padding: 20px;
    flex: 1;
    overflow-y: auto;
  }

  /* 菜单样式 - 让菜单填满剩余空间但不产生滚动条 */
  .sidebar-menu {
    border-right: none;
    width: 100%;
    flex: 1; /* 填满剩余空间 */
    overflow-y: auto; /* 仅当内容超出时才显示滚动条 */
    overflow-x: hidden; /* 隐藏横向滚动条 */
    scrollbar-width: thin; /* Firefox：细滚动条 */
    scrollbar-color: rgba(255, 255, 255, 0.3) transparent; /* Firefox：滚动条颜色 */
  }

  /* Webkit浏览器（Chrome、Safari、Edge）滚动条样式 */
  .sidebar-menu::-webkit-scrollbar {
    width: 4px; /* 滚动条宽度 */
  }

  .sidebar-menu::-webkit-scrollbar-track {
    background: transparent; /* 滚动条轨道透明 */
  }

  .sidebar-menu::-webkit-scrollbar-thumb {
    background-color: rgba(255, 255, 255, 0.3); /* 滚动条颜色 */
    border-radius: 2px; /* 滚动条圆角 */
  }

  .sidebar-menu::-webkit-scrollbar-thumb:hover {
    background-color: rgba(255, 255, 255, 0.5); /* 悬停时滚动条颜色 */
  }

  /* 覆盖Element Plus的菜单项默认样式 */
  .sidebar :deep(.el-menu-item),
  .sidebar :deep(.el-sub-menu__title) {
    margin-right: 0;
    padding-right: 20px; /* 保持适当的右侧内边距，避免文字紧贴 */
  }

  /* 确保子菜单项也有正确的内边距 */
  .sidebar :deep(.el-menu .el-menu-item) {
    padding-left: 20px !important;
    padding-right: 20px !important;
  }

  .sidebar :deep(.el-sub-menu .el-menu-item) {
    padding-left: 40px !important;
    padding-right: 20px !important;
  }
</style>
